package list_query

import (
	"fmt"
	"gorm.io/gorm"
	"yim_server/common/models"
)

type Option struct {
	PageInfo models.PageInfo
	Where    *gorm.DB // 高级查询
	Likes    []string // 模糊匹配字段
	Preload  []string // 预加载
}

// 	示例查询
//	var users []user_models.UserModel
//	count, err := ListQuery(db, User{}, Option{
//		PageInfo: PageInfo{Page: 1, Limit: 10},
//		Where:    db.Where("name LIKE ?", "%john%"),
//		Likes:    []string{"email"},
//		Preload:  []string{"Profile"},
//	})

func ListQuery[T any](db *gorm.DB, model T, option Option) (list []T, count int64, err error) {

	// 获取分页参数，并设置默认值
	page := option.PageInfo.Page
	limit := option.PageInfo.Limit

	// 计算偏移量
	offset := (page - 1) * limit

	// 创建查询基础
	query := db.Where(model)

	// 模糊匹配
	if option.PageInfo.Key != "" && len(option.Likes) > 0 {
		likeQuery := db.Where("")
		for index, column := range option.Likes {
			if index == 0 {
				// where name like '%到底%'
				likeQuery.Where(fmt.Sprintf("%s like '%%?%%'", column), option.PageInfo.Key)
			} else {
				likeQuery.Or(fmt.Sprintf("%s like '%%?%%'", column), option.PageInfo.Key)
			}
		}
		query.Where(likeQuery)
	}

	if option.Where != nil {
		query = query.Where(option.Where)
	}

	// 预加载关联关系
	for _, relation := range option.Preload {
		query = query.Preload(relation)
	}

	// 统计总数
	err = query.Model(model).Count(&count).Error
	if err != nil {
		return nil, 0, err
	}

	// 执行分页查询
	err = query.Offset(offset).Limit(limit).Find(&list).Error
	if err != nil {
		return nil, 0, err
	}

	return
}
